package me.shurufa.fragments;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.van.fanyu.library.Compresser;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.activities.AboutUsActivity;
import me.shurufa.activities.BaseInfoActivity;
import me.shurufa.activities.FeedBackActivity;
import me.shurufa.activities.MessageCenterActivity;
import me.shurufa.activities.NewLoginActivity;
import me.shurufa.activities.PhotoPickerActivity;
import me.shurufa.controller.CheckUpdateController;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.CheckVersionResp;
import me.shurufa.response.GetNoticeNumResp;
import me.shurufa.response.ProfileResp;
import me.shurufa.response.UploadAvatarResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.CircleImageView;
import me.shurufa.widget.crop.Crop;
import me.shurufa.widget.crop.util.FileUtils;
import me.shurufa.widget.simpledialog.SimpleDialog;

/**
 * "我的"界面
 * NOTICE: 消息Layout上有个红点 用来显示是否有未读消息
 */
public class NewProfileFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.user_avatar)
    CircleImageView userAvatar;

    @Bind(R.id.user_nick)
    TextView userNick;

    @Bind(R.id.user_desc)
    TextView userDesc;

    @Bind(R.id.tv_credits)
    TextView tv_credits;

    @Bind(R.id.iv_notice_num)
    ImageView iv_notice_num;

    @Bind(R.id.user_credit_layout)
    LinearLayout userCreaditLayout;    // 积分余额
    @Bind(R.id.user_baseinfo_layout)
    LinearLayout userBaseinfoLayout;   // 基础信息
    @Bind(R.id.user_message_layout)
    LinearLayout userMessageLayout;    // 消息通知
    @Bind(R.id.user_about_us_layout)
    LinearLayout userAboutUsLayout;    // 关于我们
    @Bind(R.id.user_feedback_layout)
    LinearLayout userFeedbackLayout;   // 用户反馈
    @Bind(R.id.user_logout_layout)
    LinearLayout userLogoutLayout;     // 退出登录
    @Bind(R.id.user_update_layout)
    LinearLayout userUpdateLayout;     // 版本更新

    private Dialog dialog;
    private File mTempDir;
    private CheckUpdateController mCheckController;
    private Handler mHandler = new Handler();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new_profile, container, false);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 刷新未读消息
        reqGetUnreadMessage();
    }

    @Override
    public void onDestroyView() {

        if (null != mCheckController) {
            mCheckController.release();
        }

        super.onDestroyView();
        ButterKnife.unbind(this);
        if (mTempDir.exists()) {
            FileUtils.deleteFile(mTempDir);
        }
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        //创建临时文件夹
        mTempDir = new File(Environment.getExternalStorageDirectory(), "shurufa_temp");
        if (!mTempDir.exists()) {
            mTempDir.mkdirs();
        }

        //第一次设置UI
        refresh();
        userAvatar.setOnClickListener(this);
        userCreaditLayout.setOnClickListener(this);
        userBaseinfoLayout.setOnClickListener(this);
        userMessageLayout.setOnClickListener(this);
        userAboutUsLayout.setOnClickListener(this);
        userFeedbackLayout.setOnClickListener(this);
        userLogoutLayout.setOnClickListener(this);
        userUpdateLayout.setOnClickListener(this);

        syncUserInfo();
    }

    private void syncUserInfo() {
        RequestParams params = new RequestParams();
        params.addFormDataPart("user_id", PersistenceUtils.getUserId());
        HttpRequest.post(API.GET_PROFILE, params, new HttpCallback<ProfileResp>() {

            @Override
            public void onRespSuccess(ProfileResp resp) {
                try {
                    if (resp.data == null) {
                        return;
                    }

                    // 存储积分
                    PersistenceUtils.setCredits(String.valueOf(resp.data.credits_available));
                    refresh();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(ProfileResp resp) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.user_baseinfo_layout:
                intent = new Intent(getActivity(), BaseInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.user_message_layout:
                intent = new Intent(getActivity(), MessageCenterActivity.class);
                startActivity(intent);
                break;
            // 关于我们
            case R.id.user_about_us_layout:
                intent = new Intent(getActivity(), AboutUsActivity.class);
                startActivity(intent);
                break;
            // 用户反馈
            case R.id.user_feedback_layout:
                intent = new Intent(getActivity(), FeedBackActivity.class);
                startActivity(intent);
                break;

            case R.id.user_avatar:
//                intent = new Intent(getActivity(), ModifyAvatarActivity.class);
//                startActivity(intent);
                showDialog();
                break;
            case R.id.take_photo:
                dialog.dismiss();
                checkCameraPermission();
                break;
            case R.id.take_gally:
                dialog.dismiss();
                intent = new Intent(getActivity(), PhotoPickerActivity.class);
                intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, false);
                intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_SINGLE);
                intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);
                startActivityForResult(intent, PICK_PHOTO);
                break;
            case R.id.cancel:
                dialog.dismiss();
                break;

            // 退出登录
            case R.id.user_logout_layout:
                showDlgVerifyLogout();
                break;

            case R.id.user_update_layout:
                reqUpdateVersion();
                break;
        }
    }

    private void checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCameraPermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
            if (checkCameraPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, Constants.REQUEST_CAMERA);
                return;
            } else {
                showCamera();
            }
        } else {
            showCamera();
        }
    }

    /**
     * 获取新版本
     */
    private void reqUpdateVersion() {

        RequestParams params = new RequestParams();
        HttpRequest.post(API.CHECK_UPDATE, params, new HttpCallback<CheckVersionResp>(getActivity()) {
            @Override
            public void onRespSuccess(CheckVersionResp resp) {
                try {
                    // 校验是否需要强制更新
                    CheckVersionResp.Version data = resp.data;
                    if (data == null) {
                        return;
                    }

                    mCheckController = new CheckUpdateController(getActivity());
                    // 提示强制更新
                    if (data.mustUpdate == 1) {
                        mCheckController.forceUpdate(data.downloadUrl, data.newVersion, data.whatsNew);
                        return;
                    }

                    // 提示需要更新
                    if (data.needUpdate == 1) {
                        mCheckController.needUpdate(data.downloadUrl, data.newVersion, data.whatsNew);
                        return;
                    }

                    Utils.showToast(getString(R.string.current_version_latest));
                } catch (Exception e) {
                    Utils.showToast(getString(R.string.current_version_latest));
                }
            }

            @Override
            public void onRespFailure(CheckVersionResp checkVersionResp) {

            }
        });

    }

    /**
     * 拍照时存储拍照结果的临时文件
     */
    public final static int REQUEST_CAMERA = 1;
    private static final int PICK_PHOTO = 2;
    private String mCurrentPhotoPath;

    /**
     * 选择相机
     */
    private void showCamera() {

        // 跳转到系统照相机
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            // 设置系统相机拍照后的输出路径
            // 创建临时文件
            String fileName = "Temp_camera" + String.valueOf(System.currentTimeMillis()) + ".png";
            File mTmpFile = new File(mTempDir, fileName);
            Uri uri = Uri.fromFile(mTmpFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            mCurrentPhotoPath = uri.getPath();
            startActivityForResult(cameraIntent, REQUEST_CAMERA);
        } else {
            Utils.showToast(R.string.msg_no_camera);
        }
    }

    //dialog choose 回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 相机拍照完成后，返回图片路径 打开剪裁页面
        if (requestCode == REQUEST_CAMERA) {
            if (resultCode == Activity.RESULT_OK) {
                if (!TextUtils.isEmpty(mCurrentPhotoPath)) {
                    beginCrop(Uri.fromFile(new File(mCurrentPhotoPath)));
                }
            }
        } else
            //相册选择完成后，返回图片路径 打开剪裁页面
            if (requestCode == PICK_PHOTO) {
                if (resultCode == Activity.RESULT_OK) {
                    ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                    if (result != null && result.size() > 0) {
                        beginCrop(Uri.fromFile(new File(result.get(0))));
                    }
                }
            } else
                //处理剪裁图片的回调
                if (requestCode == Crop.REQUEST_CROP) {
                    LogUtils.kLog().e("REQUEST_CROP");
                    if (resultCode == Activity.RESULT_OK) {
                        LogUtils.kLog().e("RESULT_OK");
                        Compresser compresser = new Compresser(75, (Crop.getOutput(data)).getPath());
                        compresser.doCompress(new Compresser.CompleteListener() {
                            @Override
                            public void onSuccess(String s) {
                                LogUtils.kLog().e("new Path:" + s);
                                uploadImg(s);
                            }
                        });

                    }
                }
    }

    /**
     * 上传头像
     *
     * @param path
     */
    private void uploadImg(String path) {
        File file = new File(path);
        RequestParams params = new RequestParams();
        params.addFormDataPart("image", file);

        HttpRequest.post(API.UP_AVATAR, params, new HttpCallback<UploadAvatarResp>(getActivity(), getString(R.string.submit_loading)) {
            @Override
            public void onRespSuccess(UploadAvatarResp resp) {
                try {
                    Utils.showToast(getString(R.string.avatar_edit_success));
                    if (resp.data == null) {
                        return;
                    }
                    PersistenceUtils.setAvatar(resp.data.avatar);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            refreshAvatar();
                        }
                    }, 500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(UploadAvatarResp resp) {

            }

        });
    }



    private void beginCrop(Uri source) {
        String fileName = "Temp_" + String.valueOf(System.currentTimeMillis()) + ".png";
        File cropFile = new File(mTempDir, fileName);
        Uri outputUri = Uri.fromFile(cropFile);
        new Crop(source).output(outputUri).setCropType(true).setPortrait(true).start(getActivity(), this);
    }

    private void showDialog() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_choose_photo, null);
        Button takePhoto = (Button) view.findViewById(R.id.take_photo);
        Button takeGally = (Button) view.findViewById(R.id.take_gally);
        Button cancel = (Button) view.findViewById(R.id.cancel);

        takePhoto.setOnClickListener(this);
        takeGally.setOnClickListener(this);
        cancel.setOnClickListener(this);

        dialog = new Dialog(getActivity(), R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();

        window.setWindowAnimations(R.style.menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getActivity().getWindowManager().getDefaultDisplay().getHeight();

        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (intent.getAction().equals(Constants.ACTION_FRAGMENT_REFRESH)) {
            refresh();
        }
    }

    @Override
    public void refresh() {
        if (!TextUtils.isEmpty(PersistenceUtils.getAvatar()) && userAvatar != null) {
            Glide.with(this).load((PersistenceUtils.getAvatar() + "?imageView2/2/w/100/q/85/webp"))
                    .placeholder(R.drawable.ic_def_avatar)
                    .error(R.drawable.ic_def_avatar)
                    .into(userAvatar);
        } else {
            userAvatar.setImageResource(R.drawable.ic_def_avatar);
        }

        userNick.setText(PersistenceUtils.getUsername());
        userDesc.setText(PersistenceUtils.getDescription());
        tv_credits.setText(PersistenceUtils.getCredits());

    }

    /**
     * 重新刷新头像
     */
    private void refreshAvatar() {
        if (!TextUtils.isEmpty(PersistenceUtils.getAvatar()) && userAvatar != null) {
            Glide.with(this).load((PersistenceUtils.getAvatar() + "?imageView2/2/w/100/q/85/webp"))
                    .into(userAvatar);
        } else {
            userAvatar.setImageResource(R.drawable.ic_def_avatar);
        }
    }

    @Override
    public void onDestroy() {
        if (mCheckController != null) {
            mCheckController.release();
        }
        super.onDestroy();

    }


    /**
     * 对话框 确认是否退出登录
     */
    private void showDlgVerifyLogout() {

        try {
            SimpleDialog dialog = new SimpleDialog(getActivity());
            dialog.setAnimationEnable(true);
            dialog.setContentText(getString(R.string.info_back_logout));
            dialog.setOnPositiveListener(getString(R.string.ok), new SimpleDialog.OnPositiveListener() {
                @Override
                public void onClick(SimpleDialog dialog) {
                    dialog.dismiss();
                    // 延迟150毫秒退出
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            logout();
                        }
                    }, 150);
                }
            });
            dialog.setOnNegativeListener(getString(R.string.cancel), new SimpleDialog.OnNegativeListener() {
                @Override
                public void onClick(SimpleDialog dialog) {
                    dialog.dismiss();
                }
            });
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 退出登录
     */
    private void logout() {
        EventBus.getDefault().post(new Intent(Constants.ACTION_USER_CHANGE));
        PersistenceUtils.logout();
        Intent intent = new Intent(getActivity(), NewLoginActivity.class);
        startActivity(intent);
        getActivity().finish();
    }

    /**
     * 请求未读消息
     */
    private void reqGetUnreadMessage() {

        RequestParams params = new RequestParams();
        HttpRequest.post(API.GET_NOTICE_NUM, params, new HttpCallback<GetNoticeNumResp>() {
            @Override
            public void onRespSuccess(GetNoticeNumResp resp) {
                try {
                    int unreadTotal = Integer.valueOf(resp.data.total_num);
                    iv_notice_num.setVisibility(unreadTotal > 0 ? View.VISIBLE : View.GONE);
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(GetNoticeNumResp resp) {

            }
        });

    }

}
